﻿// ********************************
// 2010.10.29
// 监控IP流量
// Author:卢融凯
// ********************************
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Lextm.SharpSnmpLib;
using Lextm.SharpSnmpLib.Messaging;
using SManage.LibExtension;
using SManage.Model.Trace;

namespace SManage.Infrastructure
{
    public class IpFlowMonitor
    {
        private IPAddress _ipAddress;

        public IpFlowMonitor(IPAddress ipAddress) {
            _ipAddress = ipAddress;
        }

        public IList<IpFlowItem> GetAllIpFlow() {
            if (_ipAddress == null) {
                return null;
            }

            // Cisco only
            var variables = new List<Variable>();

            Messenger.Walk(VersionCode.V2, new IPEndPoint(_ipAddress, 161),
                new OctetString("public"),
                new ObjectIdentifier(".1.3.6.1.4.1.9.2.4.9.1"),
                variables, 10000, WalkMode.WithinSubtree);

            var rowCount = variables.Count / 5;
            var result = new List<IpFlowItem>();
            for (int i = 0; i < rowCount; i++) {
                var ipFlowItem = new IpFlowItem { 
                    ckactSrc        = variables[0 * rowCount + i].Data.ToString(),
                    ckactDst        = variables[1 * rowCount + i].Data.ToString(),
                    ckactPkts       = variables[2 * rowCount + i].Data.ToInt32(),
                    ckactByts       = variables[3 * rowCount + i].Data.ToInt32(),
                    ckactViolation  = variables[4 * rowCount + i].Data.ToInt32()
                };
                result.Add(ipFlowItem);
            }
            return result;
        }

        public IpFlowItem GetIpFlow(string ip) {
            if (ip == null) {
                return null;
            }
            IPAddress ipa;
            if (!IPAddress.TryParse(ip, out ipa)) {
                return null;
            }

            var IpFlows = GetAllIpFlow();
            var ipFlow = IpFlows.Where(ipf => ipf.ckactSrc == ip);
            return ipFlow.Count() > 0 ? ipFlow.First() : null;
        }
    }
}
